package com.kzd.sdk.utils;

import android.app.Activity;
import android.app.Application;
import android.content.ComponentCallbacks;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Point;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;

import com.kzd.sdk.core.KZD_ApiConstance;

import java.lang.reflect.Field;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;


public class AppUtils {


    public static boolean isAppInstalled(Context context,final String pkgName) {
        if (pkgName == null || pkgName.length() == 0) return false;
        PackageManager pm = context.getPackageManager();
        try {
            return pm.getApplicationInfo(pkgName, 0).enabled;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }

    public static void launchApp(Context context,final String packageName) {
        Intent LaunchIntent = context.getPackageManager()
                .getLaunchIntentForPackage(packageName);
        context.startActivity(LaunchIntent);
    }

    public static void launchBrowser(Context context,final String url) {
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        context.startActivity(intent);
    }

    public static int dp2px(final float dpValue) {
        final float scale = Resources.getSystem().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static int getAppScreenWidth(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        if (wm == null) return -1;
        Point point = new Point();
        wm.getDefaultDisplay().getSize(point);
        return point.x;
    }

    public static int getAppScreenHeight(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        if (wm == null) return -1;
        Point point = new Point();
        wm.getDefaultDisplay().getSize(point);
        return point.y;
    }

    public static int getLayoutId(Context paramContext, String paramString) {
        return paramContext.getResources().getIdentifier(paramString, "layout",
                paramContext.getPackageName());
    }

    public static int getStringId(Context paramContext, String paramString) {
        return paramContext.getResources().getIdentifier(paramString, "string",
                paramContext.getPackageName());
    }

    public static int getDrawableId(Context paramContext, String paramString) {
        return paramContext.getResources().getIdentifier(paramString,
                "drawable", paramContext.getPackageName());
    }

    public static int getStyleId(Context paramContext, String paramString) {
        return paramContext.getResources().getIdentifier(paramString,
                "style", paramContext.getPackageName());
    }

    public static int getId(Context paramContext, String paramString) {
        return paramContext.getResources().getIdentifier(paramString, "id", paramContext.getPackageName());
    }

    public static int getColorId(Context paramContext, String paramString) {
        return paramContext.getResources().getIdentifier(paramString,
                "color", paramContext.getPackageName());
    }

    public static int getArrayId(Context paramContext, String paramString) {
        return paramContext.getResources().getIdentifier(paramString,
                "array", paramContext.getPackageName());
    }

    public static int getAttrId(Context paramContext, String paramString) {
        return paramContext.getResources().getIdentifier(paramString,
                "attr", paramContext.getPackageName());
    }



    public static String md5(String string) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes());
            String result = "";
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result += temp;
            }
            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static boolean isMobileExact(final CharSequence input) {
        return isMatch("^((13[0-9])|(14[579])|(15[0-35-9])|(16[2567])|(17[0-35-8])|(18[0-9])|(19[0-35-9]))\\d{8}$", input);
    }

    public static boolean isMatch(final String regex, final CharSequence input) {
        return input != null && input.length() > 0 && Pattern.matches(regex, input);
    }

//    public static Activity getTopActivity() {
//        List<Activity> activityList = getActivitiesByReflect();
//        for (Activity activity : activityList) {
//            if (!(activity != null && !activity.isFinishing()
//                    && (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1 || !activity.isDestroyed()))) {
//                continue;
//            }
//            return activity;
//        }
//        return null;
//    }

//    private static List<Activity> getActivitiesByReflect() {
//        LinkedList<Activity> list = new LinkedList<>();
//        Activity topActivity = null;
//        try {
//            Object activityThread = getActivityThread();
//            Field mActivitiesField = activityThread.getClass().getDeclaredField("mActivities");
//            mActivitiesField.setAccessible(true);
//            Object mActivities = mActivitiesField.get(activityThread);
//            if (!(mActivities instanceof Map)) {
//                return list;
//            }
//            Map<Object, Object> binder_activityClientRecord_map = (Map<Object, Object>) mActivities;
//            for (Object activityRecord : binder_activityClientRecord_map.values()) {
//                Class activityClientRecordClass = activityRecord.getClass();
//                Field activityField = activityClientRecordClass.getDeclaredField("activity");
//                activityField.setAccessible(true);
//                Activity activity = (Activity) activityField.get(activityRecord);
//                if (topActivity == null) {
//                    Field pausedField = activityClientRecordClass.getDeclaredField("paused");
//                    pausedField.setAccessible(true);
//                    if (!pausedField.getBoolean(activityRecord)) {
//                        topActivity = activity;
//                    } else {
//                        list.add(activity);
//                    }
//                } else {
//                    list.add(activity);
//                }
//            }
//        } catch (Exception e) {
//            Log.e("UtilsActivityLifecycle", "getActivitiesByReflect: " + e.getMessage());
//        }
//        if (topActivity != null) {
//            list.addFirst(topActivity);
//        }
//        return list;
//    }

//    private static Object getActivityThread() {
//        Object activityThread = getActivityThreadInActivityThreadStaticField();
//        if (activityThread != null) return activityThread;
//        return getActivityThreadInActivityThreadStaticMethod();
//    }

//    private static Object getActivityThreadInActivityThreadStaticField() {
//        try {
//            Class activityThreadClass = Class.forName("android.app.ActivityThread");
//            Field sCurrentActivityThreadField = activityThreadClass.getDeclaredField("sCurrentActivityThread");
//            sCurrentActivityThreadField.setAccessible(true);
//            return sCurrentActivityThreadField.get(null);
//        } catch (Exception e) {
//            Log.e("UtilsActivityLifecycle", "getActivityThreadInActivityThreadStaticField: " + e.getMessage());
//            return null;
//        }
//    }

//    private static Object getActivityThreadInActivityThreadStaticMethod() {
//        try {
//            Class activityThreadClass = Class.forName("android.app.ActivityThread");
//            return activityThreadClass.getMethod("currentActivityThread").invoke(null);
//        } catch (Exception e) {
//            Log.e("UtilsActivityLifecycle", "getActivityThreadInActivityThreadStaticMethod: " + e.getMessage());
//            return null;
//        }
//    }

    private static float sNoncompatDensity;
    private static float sNoncompatScalodDensity;

    public static void setCustomDensity(Activity activity, final Application application) {
        final DisplayMetrics appDisplayMetrics = application.getResources().getDisplayMetrics();
        if (sNoncompatDensity == 0) {
            sNoncompatDensity = appDisplayMetrics.density;
            sNoncompatScalodDensity = appDisplayMetrics.scaledDensity;
            application.registerComponentCallbacks(new ComponentCallbacks() {
                @Override
                public void onConfigurationChanged(Configuration newConfig) {
                    if (newConfig != null && newConfig.fontScale > 0) {
                        sNoncompatScalodDensity = application.getResources().getDisplayMetrics().scaledDensity;
                    }
                }

                @Override
                public void onLowMemory() {

                }
            });
        }

        float targetDensity = 0;
        if (application.getResources().getConfiguration().orientation
                == Configuration.ORIENTATION_PORTRAIT) {
            targetDensity = appDisplayMetrics.widthPixels / 360;
        } else {
            targetDensity = appDisplayMetrics.widthPixels / 640;
        }
        final float targetScaledDensity = targetDensity * (sNoncompatScalodDensity / sNoncompatDensity);
        final int targetDensityDpi = (int) (160 * targetDensity);

        appDisplayMetrics.density = targetDensity;
        appDisplayMetrics.scaledDensity = targetScaledDensity;
        appDisplayMetrics.densityDpi = targetDensityDpi;

        final DisplayMetrics activityDisplayMetrics = activity.getResources().getDisplayMetrics();
        activityDisplayMetrics.density = targetDensity;
        activityDisplayMetrics.scaledDensity = targetScaledDensity;
        activityDisplayMetrics.densityDpi = targetDensityDpi;

    }

}
